import copy
import os
import sys

import pyautogui
import PygameCrew as pycr
from calca import mltsplit

from asset.base import *

file_path=""
blank_path="./levels/blank"+default_suffix
tmp=[]
def dirof(path:str):return '/'.join(mltsplit(path,'/','\\')[:-1])
def startup(result:str=None):
    global file_path,tmp
    while result is None:
        result=pyautogui.prompt("Please input your file name to be edited.")
        if result is None:sys.exit()
        result=result.lower()
        for r in blocked_names:
            if result.find(r) != -1:
                pyautogui.alert("Please use other names and try again.","This Name is Unavailable!")
                result=None
    result:str
    result=result.replace(r"_o_/","official/")
    if result.find('/')==-1 and result.find('\\')==-1:file_path="./levels/default/"+result+default_suffix
    else:file_path="./levels/"+result+default_suffix
    for d in direct_dirs:
        for suffix in support_suffix:
            p="./levels/"+d+result+suffix
            if os.path.exists(p):file_path=p
    if not os.path.exists(file_path):
        if not os.path.exists(dirof(file_path)):
            os.mkdir(dirof(file_path))
        with open(file_path,"w") as file:
            file.write(open(blank_path,"r").read())
    tmp=[]
    exec(open(file_path,"r").read()+"\ntmp.append(__level__)\ntmp.append(__levelname__)\ntmp.append(__version__)")
    text="Editing "+mltsplit(file_path,'/','\\')[-1]
    pygame.display.set_caption(text)
    return tuple(tmp)+(result,)
def exit_save(all:list,name:str="blank",version:str="0.0.1"):
    blank=open(blank_path,"r").read()
    text="\n"
    for a in all:
        text+=pycr.stringify(a)+",\n"
    text=blank.replace("#-INPUT-#",text)
    text=text.replace("__levelname__=\"blank\"","__levelname__="+pycr.stringify(name))
    text=text.replace("__version__=\"0.0.1\"","__version__="+pycr.stringify(version))
    save()
    with open(file_path,"w") as file:
        file.write(text)
        
        
        
file_path="./save"
if not os.path.exists(file_path):
    with open(file_path,"x"):...
igvar:dict=copy.deepcopy(Default)
with open(file_path,"r") as file:
    while True:
        try:
            exec("igvar="+file.read())
            if type(igvar) != dict:raise SyntaxError
            break
        except SyntaxError:
            with open(file_path,"w") as filew:
                filew.write(pycr.stringify(Default))
def save():
    with open(file_path,"w") as file:
        file.write(pycr.stringify(igvar))
